const express = require('express');  
const fs = require('fs');  
const path = require('path');  
// const https = require('https');
const tls = require('tls');
const app = express();  
const PORT = 3000;  
  
// 允许跨域请求  
app.use((req, res, next) => {  
    res.header("Access-Control-Allow-Origin", "*");  
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");  
    next();  
});  
// 使用express.json()中间件来解析JSON格式的请求体  
app.use(express.json()); 
  
// 文件树生成函数  
function listFiles(dirPath, result = []) {  
    const files = fs.readdirSync(dirPath);  
    files.forEach(file => {  
        const filePath = path.join(dirPath, file);  
        const stats = fs.statSync(filePath);  
        if (stats.isDirectory()) {  
            result.push({  
                name: file,  
                type: 'directory',  
                children: listFiles(filePath),
                title: file,
                // key设置为树路径，方便前端使用
                key: filePath.replace(/\\/g, '/') // 将路径中的反斜杠替换为正斜杠
            });  
        } else if (file.endsWith('.md')) {  
            result.push({  
                name: file,
                type: 'file',
                title: file,
                key: filePath.replace(/\\/g, '/') // 将路径中的反斜杠替换为正斜杠
            });  
        }  
    });  
    return result;  
}  
  
const mysql = require('mysql2/promise');  
const { title } = require('process');
  
async function getConnection() {  
    return await mysql.createConnection({  
        host: '139.198.108.126',
        port: 3307,
        user: 'root',  
        password: 'Root123456!',  
        database: 'test'  
    });  
}

async function fetchCertificateInfo(domain, port = 443) {
    return new Promise((resolve, reject) => {
        const options = {
            host: domain,
            port: port,
            rejectUnauthorized: false, // 不验证证书
            timeout: 3000 // 设置超时时间为3秒
        };

        const secureConnection = tls.connect(options, () => {
            const peerCertificate = secureConnection.getPeerCertificate();
            
            // 假设issuer和subject是类似{ C: 'Country', O: 'Organization', CN: 'Common Name' }的对象  
            const { C: issuerC, O: issuerO, CN: issuerCN } = peerCertificate.issuer;  
            const { C: subjectC, O: subjectO, CN: subjectCN } = peerCertificate.subject; 

            resolve({
                domain,  
                issuerC,  
                issuerO,  
                issuerCN,  
                subjectC,  
                subjectO,  
                subjectCN,  
                valid_from: new Date(peerCertificate.valid_from).toISOString(),
                valid_to: new Date(peerCertificate.valid_to).toISOString(),
                daysUsed: Math.round((new Date() - new Date(peerCertificate.valid_from)) / (1000 * 60 * 60 * 24)),
                daysLeft: Math.round((new Date(peerCertificate.valid_to) - new Date()) / (1000 * 60 * 60 * 24))
            });

            // 关闭连接
            secureConnection.end();
        });
        
        secureConnection.on('error', (err) => {
            // reject(err);
            if (err.code == 'ETIMEDOUT') {
                // 继续尝试下一个域名
                resolve();
            }
        });
        // 设置超时处理
        secureConnection.on('timeout', () => {
            // reject(new Error('Connection timed out'));
            resolve();
        });
    });
}
// 示例路由：获取域名列表及其证书信息  
app.get('/domains/certificates', async (req, res) => {
    try {
        const connection = await getConnection();
        const [rows] = await connection.execute('SELECT domain, port, des FROM domains');

        const certificates = await Promise.all(rows.map(async row => {
            const certificate = await fetchCertificateInfo(row.domain, row.port);
            return {
                ...row,
                ...certificate
            };
        }));
        res.json(certificates);
    } catch (error) {
        console.error(error);
        res.status(500).send('Internal Server Error');
    }
});

// API接口  
app.get('/files', (req, res) => {  
    const dirPath = req.query.dirPath || '.'; // 默认当前目录  
    try {  
        const fileTree = listFiles(dirPath);  
        res.json(fileTree);  
    } catch (error) {  
        res.status(500).json({ error: error.message });  
    }  
});  
  
// 获取文件内容
app.get('/fileContent', (req, res) => {
    const filePath = req.query.filePath;
    try {
        const content = fs.readFileSync(filePath, 'utf8');
        res.json({ content });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

// 更新文件内容
app.post('/updateFile', (req, res) => {
    const filePath = req.body.filePath; // 文件路径
    const content = req.body.content; // 文件内容
    try {
        fs.writeFileSync(filePath, content);  
        res.json({ message: 'File updated successfully' });  
    } catch (error) {  
        res.status(500).json({ error: error.message });
    } 
});

app.listen(PORT, () => {  
    console.log(`Server is running on port ${PORT}`);  
});